package xyz.ranyh.jobclient.http;

import android.os.AsyncTask;
import android.provider.Settings;
import android.util.Log;

import org.json.JSONObject;
import org.json.JSONTokener;

import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by rany on 12/27/16.
 */

public abstract class RegisterTask extends AsyncTask<Void, Void, JSONObject> {
    OkHttpClient client = new OkHttpClient();
    int statusCode;
    String mEmail;
    String mPassword;
    String mNickname;
    String msg;

    public RegisterTask(String email, String password, String nickname) {
        mEmail = email;
        mPassword = password;
        mNickname = nickname;
    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        String postBody = "{\"username\": \"" + mEmail +"\", \"password\": \""+
                mPassword + "\", \"nickname\": \""+ mNickname +"\"}";
        Log.d("Post body", postBody);
        RequestBody reqBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postBody);
        try {
            String credential = Credentials.basic(Resource.getInstance().token, "");
            Request request =  new Request.Builder()
                    .post(reqBody)
                    .url(Url.UESR_URL)
                    .addHeader("Authorization", credential)
                    .addHeader("accept", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            statusCode = response.code();

            String responseText = response.body().string();
            Log.d("Response text", responseText);

            JSONTokener resJson = new JSONTokener(responseText);
            JSONObject bodyJson = (JSONObject) resJson.nextValue();

            msg = bodyJson.getString("message");
            Log.d("msg", msg);

            return bodyJson;

        } catch (Exception e) {
            Log.d("Register task", e.getMessage());
        }
        return null;
    }
}
